var { pinyin } = pinyinPro;
const apikey = "&appid=" + "5bc2b4f40acfffa046713955a4370d52";
const url = "https://api.openweathermap.org/data/2.5/weather?q=";
let city = "foshan";

let searchContainer;
let weatherContainer;
window.onload = function () {
  findSearchContainer();
  findWeatherContainer();
};
//用于处理加载中的显示效果
function findSearchContainer() {
  searchContainer = document.querySelector(".search-container");
  if (!searchContainer) {
    console.error("无法找到.search-container元素");
  }
}
function addOnLoadClass() {
  if (searchContainer) {
    searchContainer.classList.add("onload");
  } else {
    console.error(
      ".search-container元素未定义，请先调用findSearchContainer()函数"
    );
  }
}
function removeOnLoadClass() {
  if (searchContainer) {
    searchContainer.classList.remove("onload");
  } else {
    console.error(
      ".search-container元素未定义，请先调用findSearchContainer()函数"
    );
  }
}
// 用于在weather-container中末尾插入新的div以显示天气信息
function findWeatherContainer() {
  weatherContainer = document.querySelector(".weather-container");
  if (!weatherContainer) {
    console.error("无法找到.weather-container元素");
  }
}
function appendDivToWeatherContainer(content) {
  if (weatherContainer) {
    var newDiv = document.createElement("div");
    newDiv.textContent = content;
    weatherContainer.appendChild(newDiv);
  } else {
    console.error(
      "weather-container元素未定义，请先调用findWeatherContainer()函数"
    );
  }
}
function clearWeatherContainer() {
  if (weatherContainer) {
    weatherContainer.innerHTML = "";
  } else {
    console.error(
      "weather-container元素未定义，请先调用findWeatherContainer()函数"
    );
  }
}
// 用于在weather-container中插入天气图标
function insertWeatherIcon(data) {
  if (!data || !data.weather || !data.weather[0] || !data.weather[0].icon) {
    console.error("数据对象或weather数组中的icon属性不存在");
    return;
  }

  var iconUrl =
    "http://openweathermap.org/img/wn/" + data.weather[0].icon + "@2x.png";

  if (!weatherContainer) {
    findWeatherContainer();
    if (!weatherContainer) {
      console.error("无法找到.weather-container元素");
      return;
    }
  }

  var weatherIconSpan = document.createElement("span");
  weatherIconSpan.classList.add("weather-icon");

  var img = document.createElement("img");
  img.src = iconUrl;
  img.alt = "Weather Icon";

  weatherIconSpan.appendChild(img);
  weatherContainer.appendChild(weatherIconSpan);

  var newDiv = document.createElement("div");
  newDiv.textContent = data.weather[0].description;
  newDiv.classList.add("weather-description");
  weatherIconSpan.appendChild(newDiv);
}

//appendDivToWeatherContainer(content) 在weather-container中末尾插入新的div以显示天气信息
//addOnLoadClass() removeOnLoadClass() 用于处理加载中的显示效果
//insertWeatherIcon(data) 在weather-container中插入天气图标
//clearWeatherContainer() 清除weather-container中的所有内容

//发送请求
function fetchWeather() {
  addOnLoadClass();
  fetch(url + city + apikey + "&units=metric&lang=zh_cn")
    .then((response) => response.json())
    .then((data) => {
      // data.json
      switch (data.cod) {
        case 200:
          clearWeatherContainer();
          appendDivToWeatherContainer(data.sys.country + " : " + data.name);
          appendDivToWeatherContainer(
            "经纬: " + data.coord.lon + " , " + data.coord.lat
          );
          appendDivToWeatherContainer("温度 : " + data.main.temp + " ℃");
          appendDivToWeatherContainer(
            "体感温度 : " + data.main.feels_like + " ℃"
          );
          appendDivToWeatherContainer("湿度 : " + data.main.humidity + " %");
          appendDivToWeatherContainer("风速 : " + data.wind.speed + " m/s");
          insertWeatherIcon(data);
          break;
        case "400":
          clearWeatherContainer();
          appendDivToWeatherContainer("啊哦，出错了,可能没有输入内容咩");
          break;
        case "404":
          clearWeatherContainer();
          appendDivToWeatherContainer("没有该城市哦!");
          break;
        default:
          clearWeatherContainer();
          appendDivToWeatherContainer("啊哦，出错了,再试一次吧。");
          break;
      }
      console.log(data);
      removeOnLoadClass();
    })
    .catch((error) => {
      // Failed to fetch
      clearWeatherContainer();
      appendDivToWeatherContainer("请检查网络连接。");
      console.error(
        "There has been a problem with your fetch operation:",
        error
      );
      removeOnLoadClass();
    });
}

function search() {
  city = document.querySelector(".search-bar").value;
  city = fixcityNameFormat(city);
  // console.log(city = fixcityNameFormat(city));
  //   console.log(url + city + apikey);
  if (city == "") {
    clearWeatherContainer();
    appendDivToWeatherContainer("啊哦，出错了,可能没有输入内容咩");
    return;
  }
  fetchWeather();
}
// 对传入的city名进行处理
function fixcityNameFormat(city){
  city = pinyin(city, { toneType: "none" });
  return city.replace(/\s/g, '');
}
// 一个enter事件监听
document.addEventListener("DOMContentLoaded", (event) => {
  const searchInput = document.getElementById("search-input");
  searchInput.addEventListener("keydown", function (event) {
    if (event.key === "Enter") {
      event.preventDefault();
      search();
    }
  });
});

// //控制输入城市名时不要标点符号
// function restrictPunctuation(event) {
//   var punctuation = /[!"#$%&'()*+,\-.\/:;<=>?@[\]^_`{|}~]/g;
//   if (punctuation.test(event.key)) {
//     event.preventDefault();
//     // alert('标点符号不被允许');
//   }
// }
/////////////////
// icon获取示例
// https://openweathermap.org/img/wn/@2x.png
// 有用的字段
// {
//     "coord": {
//         "lon": 113.1315,     //经度
//         "lat": 23.0268       //纬度
//     },
//     "weather": [
//         {
//             "description": "多云",
//             "icon": "04n"          //天气图标
//         }
//     ],
//     "main": {
//         "temp": 29.02,           //温度       //摄氏度
//         "feels_like": 35.47,     //体感温度
//         "humidity": 83,           //湿度 %
//     },
//     "wind": {
//         "speed": 2.93,           //风速 m/s
//     },
//     "sys": {
//         "country": "CN",        //国家
//     },
//     "name": "Foshan",     //城市名
//     "cod": 200
// }
//
//cod详情
// 400 请求参数或值不正确
// 401 APItoken错误
// 429 太多请求
// 5xx 服务器错误
